<?php
namespace Cyfy\Modules\FileManager;
use \Cyfy\Modules\Objects;

/**
 * Module for uploading files and inserting them into TinyMCE.
 *
 * @author Dandelion
 * @version 0.1
 */

class Module extends \Cyfy\Module
{
    /**
     * Icon size
     * @var int
     */
    static private $size = 22;
    
    /**
     * Filetypes, which we have an icon for.
     * @var array
     */
    static private $filetypes = array("folder", "avi","css","deb","doc","exe","html","jpg","js","mp3","mpg","pdf","php","png","qt","rpm", "swf","tar","txt","wma","xls");
    
    /**
     * Opened in window?
     * @var bool
     */
    static private $window = false;

    /**
     * Administration UI
     *
     * @param string Admin name
     * @return mixed
     */
    static function administration($name="")
    {
       	switch($name)
        {
            case "fileManager":
                return self :: fileManager();
                
            case "":
                return array(
                    "fileManager" => array("name" => self :: t(10), "description" => self :: t(20), "permission"=> "use")
                );
		}	
        return false;
    }
    
    /**
     * AJAX callbacks
     * @param string Callback name
     * @return mixed
     */
    static function ajax($name)
    {
        if(!\Cyfy\Cyfy ::  permission("FileManager", "use"))
        {
            return false;
        }
        
        switch($name)
        {
            case "treeDir":
                return self :: tree();
            case "readDir":
                return self :: dir();
            case "deleteFiles":
                return self :: ajaxDelete();
           // case "chmodFiles":
           //     return self :: ajaxChmod();
        }
        return false;
    }

    /**
     * Method which loads FM
     * @return string HTML content.
     */
    static private function fileManager()
    {
        // load UI
        \Cyfy\Modules\jquery\Plugins :: load("jqueryUI");
        
        if($_POST["dir"]){
            $output .= \Cyfy\Cyfy ::  javaScript("fileManager.dir = '{$_POST["dir"]}'", "inline");
        }        
        
       
    
        if(self :: $window)
        {
            $url = \Cyfy\Cyfy ::  getSourcePath(\Cyfy\Cyfy ::  $filesDir);
            \Cyfy\Cyfy ::  javascript(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/TinyMCE/tinymce/jscripts/tiny_mce/tiny_mce_popup.js"), "file", "header");
            $js = <<<JAVASCRIPT
fileManager.window = true;

var FileBrowserDialogue = {
  init : function () {
      // Here goes your code for setting your custom things onLoad.
  },
  mySubmit : function (file) {
      var win = tinyMCEPopup.getWindowArg("window");
      var URL = "{$url}" + file;
      
      // insert information now
      win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = URL;

      // are we an image browser
      if (typeof(win.ImageDialog) != "undefined")
      {
          // we are, so update image dimensions and preview if necessary
          if (win.ImageDialog.getImageData) win.ImageDialog.getImageData();
          if (win.ImageDialog.showPreviewImage) win.ImageDialog.showPreviewImage(URL);
      }
      // close popup window
      tinyMCEPopup.close();
  }
}
tinyMCEPopup.onInit.add(FileBrowserDialogue.init, FileBrowserDialogue);
JAVASCRIPT;
            $output .= \Cyfy\Cyfy ::  javascript($js, "inline");
    }
        $output .= "<div id=\"fileManager\">\n";
        $output .= "<input type=\"hidden\" id=\"fileManagerType\" value=\"{$_GET["type"]}\" />\n";
        $output .= "<form style=\"margin:0px;padding:0px;width:95%;background:transparent;border-width:0px\" id=\"fileManagerPathForm\" method=\"post\" onsubmit=\"return false;\">" . self :: t(60) . ":&nbsp;<input style=\"width:50%;font-size:10pt;\" type=\"text\" id=\"fileManagerPath\" styl/></form>\n";
    
        if(self :: $window){
            $output .= self :: preview();
        }
    
        $output .= "<div id=\"fileManagerLeft\">\n";
        $output .= "<h3>" . self :: t(130) . "</h3>\n";
        $output .= "    <div id=\"fileManagerTree\">" . self :: tree("") . "</div>\n";
        $output .= "<h3>" . self :: t(140) . "</h3>\n";
        $output .= "    <div id=\"fileManagerControls\" class=\"form-buttons\">" . self :: controls() . "</div>\n";
        $output .= "</div>\n";

        $output .= "<div id=\"fileManagerFiles\">" . self :: dir("", $window) . "</div>\n";
    
        \Cyfy\Cyfy ::  CSS(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/FileManager/filemanager.css"));
        \Cyfy\Cyfy ::  javaScript(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/FileManager/scripts.js"), "file");
        $output .= "</div>\n";
        
         // FILE UPLOAD
        $c = new Objects\Collapsible();
        $form = new Forms\Upload();
        $c -> setClass("fileUploadFormC");
        $c -> setData(self :: t(110), $form -> show(), true);
        $output .= $c -> show();
    
        // NEW DIRECTORY
        $c = new Objects\Collapsible();
        $form = new Forms\MakeDirectory();
        $c -> setClass("makeDirectoryFormC");
        $c -> setData(self :: t(120), $form -> show(), true);
        $output .= $c -> show();
    
        return $output; 
    }
  
    /**
     * Returns window.
     * @return string HTML content
     */
    static function get($name)
    {
        if($name=="window")
        {
            \Cyfy\Template :: useFile("fmwindow.tpl", "FileManager");
            self :: $window = true;
            return self :: fileManager();
        }  
    }
  
    /**
     * Preview part of FM, only when in window mode
     * @return string HTML content
     */  
    static function preview()
    {
        $output = "<div id=\"fileManagerPreview\"><img src=\"" . \Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/FileManager/images/empty.png") . "\" id=\"fileManagerPreviewImage\" /><p id=\"fileManagerPreviewFilename\"></p></div>\n";
        return $output;  
    }
  
    /**
     * Returns tree for dir.
     * @param string Directory
     * @return string HTML content
     */
    static function tree($dir = "")
    {
        if($_POST["dirt"]){
            $dir = $_POST["dirt"];
        }
        $dir = ($dir=="") ? "/" : $dir;
    
        $imageFile = "<img style=\"border-width:0px;padding:0;margin:0 15px;border-radius:0px;background:transparent;\" src=\"". \Cyfy\Cyfy ::  getSourcePath( "Cyfy/Modules/FileManager/icons/" . self :: $size . "/folder.png") ."\" alt=\"" . self :: t(150) . "\" />\n";
    
        $output = "<ul>\n";
        foreach(self::readTree($dir) as $directory){
            $output .= "<li><span class=\"plus\" onclick=\"fileManager.treeDir('{$dir}{$directory["file"]}/', $(this))\"> + </span><span class=\"link\" onclick=\" fileManager.colorize($(this).parent()); fileManager.readDir('{$dir}{$directory["file"]}');\">" . $imageFile . $directory["basename"] . "</span></li>\n";
        }    
        $output .= "</ul>\n";
  
        return $output;
    }

    /**
     * Returns a directory contents
     * @param string Directory
     * @param bool windowed
     * @return HTML output
     */
    static function dir($dir = "", $windowed = false)
    {
        if(!\Cyfy\Cyfy ::  permission("FileManager", "use"))
        {
            return false;
        } 
      
        // loads the basics
        if($_POST["dir"]){
            $dir = $_POST["dir"];
        }
        if($_POST["windowed"]){
            $windowed = $_POST["windowed"];
        }

        // disable ../
        if(strpos($dir, "../") !== false)
        {
            \Cyfy\Message :: set(self :: t(160), \Cyfy\Message::ERROR);
            return false;
        }

        if(file_exists(\Cyfy\Cyfy ::  $filesDir . $dir) == false)
        {
            \Cyfy\Message :: set(self :: t(171, array($dir)), \Cyfy\Message::ERROR);
            return false;
        }
         
        $windowed = ($windowed == false) ? 0 : 1;
      
        // table with files
        $table = new Objects\Table("", "fileManagerFilesTable");
        $table -> header(array("filename" => self :: t(30), "ext"=> self :: t(40), "size"=> self :: t(50)));
     
        // reads files
        $files = self :: readDir($dir);
      
        if(count($files))
        {
            foreach($files as $file)
            {
                // path of the file
                $path = $dir . $file["basename"];
          
                $linkA = "";
                $linkB = "";
          
          
                // if type = file
                if($file["type"]=="file")
                {
                    $size = filesizeFormated($file["filesize"]);
                    $file["extension"] = strtolower($file["extension"]);
                    $image = $file["extension"];
                    if(in_array($image, self :: $filetypes) == false)
                    {
                        $image = "file";
                    }
                    $imageFile = "<img src=\"" . \Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/FileManager/icons/" . self :: $size ."/".$image.".png") ."\" alt=\"\" width=\"22\" style=\"border-width:0px;padding:0;margin:0\" height=\"22\" />";
                    $class = "fileManagerFile";
                }else{
                    // type = folder
                    $imageFile = "<img src=\"" . \Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/FileManager/icons/" . self :: $size ."/folder.png") ."\" alt=\"" . self::t(150) . "\" style=\"border-width:0px;padding:0;margin:0\" width=\"22\" height=\"22\" />";
                    $size = "DIR";   
                    $file["extension"] = "";          
                    $class = "fileManagerFolder";
                }
          
                $table -> row(array($imageFile . $file["basename"], $file["extension"], $size), "", false, "", $class);
          
          /*
            // delete button
            if($file["type"]=="file"){
              $output .= "<input type=\"submit\" class=\"fmDelete\" onclick=\"if(confirm('".t("Are you sure to delete %s?", array($file["basename"]))."')){ fMdeleteFile('{$path}');  } return false;\" value=\"".t("Delete")."\">\n";
            }else{
              $output .= "<input type=\"submit\" class=\"fmDelete\" onclick=\"if(confirm('".t("Are you sure to delete folder %s and all its contents?", array($file["basename"]))."')){ fMdeleteFolder('{$path}');  } return false;\" value=\"".t("Delete")."\">\n";
            }   
          
          }else{
          // choose button for Window
            if($file["type"]=="file"){
              $output .= "<input type=\"submit\" class=\"fmDelete\" onclick=\"FileBrowserDialogue.mySubmit('{$path}'); return false;\" value=\"".t("Choose")."\">\n";
            }
          }
  */
            }  
        }
        else
        {
            $table->row(array(self :: t(180), "", ""));
        }
      
        return $table->show();
    }

    /**
     * Reads a dir and formats the data and returns them as an array
     * @param string dir
     * @return array
     */
    static private function readDir($dir)
    {
        $files = array();
        $directories = array();
        $source = scandir(\Cyfy\Cyfy ::  $filesDir . $dir);
        unset($source[0]);
        // chroot
        if($dir=="")
        {
            unset($source[1]);
        }
        foreach($source as $file)
        {
            $type = filetype(\Cyfy\Cyfy ::  $filesDir . $dir . $file);
            
            // FILE
            if($type == "file")
            {
                $filesize = filesize(\Cyfy\Cyfy ::  $filesDir . $dir . $file);
                $info1 = array("filesize"=> $filesize, "type"=>"file");
                $info2 = pathinfo($file);
                $files[] = array_merge($info1, $info2);
            }
            
            // DIR
            else
            {
                $info1 = array("filesize"=> "DIR", "type"=>"directory");
                $info2 = pathinfo($file);
                $directories[] = array_merge($info1, $info2);
            }
        }
        return array_merge($directories, $files);
    }
  
    /**
     * Reads a tree
     * @param string dir
     * @return array
     */
    static function readTree($dir)
    {
        $directories = array();
        $source = scandir(\Cyfy\Cyfy ::  $filesDir . $dir);
        unset($source[0]);
        unset($source[1]);
        
        foreach($source as $file)
        {
            if(filetype(realpath(\Cyfy\Cyfy ::  $filesDir . $dir . $file)) != "file")
            {
                $info = pathinfo($file);
                $info["file"] = $file;
                $directories[] = $info;
            }
        }
        return $directories;
    }
    
    /**
     * Controls for handling files
     * @return string HTML content
     */    
    static private function controls()
    {
        if(self :: $window == true) return "";

        $output = "<input type=\"submit\" value=\"" . self :: t(190) ."\" onclick=\"if(fileManager.selectedFilesString != ''){ if(confirm('" . self :: t(200) . "\\n' + fileManager.selectedFilesString)) { fileManager.deleteSelected(); } }else{ alert('". self :: t(210) ."'); }return false;\" /><br /><br />";

        // AN ATTEMP TO CREATE CHMOD - doesn't work much
        
        //  $output .= "<input type=\"submit\" value=\"" . \Cyfy\Cyfy :: t("Chmod to 0777") ."\" onclick=\"if(fileManager.selectedFilesString != ''){ if(confirm('" . \Cyfy\Cyfy :: t("Are you sure to set these files writable for anyone?"). "\\n' + fileManager.selectedFilesString)) { fileManager.chmodSelected(); } }else{ alert('". \Cyfy\Cyfy :: t("No files selected.") ."'); }return false;\" />";
    
        return $output;
    }
    
    /** 
     * Deletes files from post.
     */
    static private function ajaxDelete()
    {
        foreach($_POST["files"] as $file)
        {
            if($file == "..") continue;
            
            $filename = \Cyfy\Cyfy :: $filesDir . $_POST["prefixDirectory"] . $file;
            if(!\Cyfy\Cyfy ::  delete($filename))
            {
                \Cyfy\Message :: set(self :: t(221, array($filename)), \Cyfy\Message::ERROR);
            }
        }   
        \Cyfy\Message :: set(self :: t(230));
    }
    
    /** 
     * Chmods files from post.
     */
    static private function ajaxChmod()
    {
        foreach($_POST["files"] as $file)
        {
            if($file == "..") continue;
            
            $filename = \Cyfy\Cyfy :: $filesDir . $_POST["prefixDirectory"] . $file;
            if(!chmod($filename, 0777))
            {
                \Cyfy\Message :: set(self :: t(241, array($filename)), \Cyfy\Message::ERROR);
            }
        }   
        \Cyfy\Message :: set(self :: t(250));
    }
}

